using Quartz;


namespace Jobs.Configurations;
public class JobHostedService : IHostedService
{
    private readonly ISchedulerFactory _schedulerFactory;

    private readonly IEnumerable<JobSchedule> _jobSchedules;

    public JobHostedService(ISchedulerFactory schedulerFactory, IEnumerable<JobSchedule> jobSchedules)
    {
        this._schedulerFactory = schedulerFactory;
        this._jobSchedules = jobSchedules;
    }

    public IScheduler _scheduler { get; set; }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        _scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
        foreach (var item in _jobSchedules)
        {
            var job = CreateJob(item);
            var trigger = CreateTrigger(item);
            await _scheduler.ScheduleJob(job, trigger, cancellationToken);
        }
        await _scheduler.Start(cancellationToken);
    }


    public async Task StopAsync(CancellationToken cancellationToken)
    {
        await _scheduler.Shutdown(cancellationToken);
    }
    private static IJobDetail CreateJob(JobSchedule schedule)
    {
        Type jobType = schedule.JobType;
        return JobBuilder.Create(jobType).WithIdentity(jobType.FullName).WithDescription(jobType.Name)
            .Build();
    }

    private static ITrigger CreateTrigger(JobSchedule schedule)
    {
        return TriggerBuilder.Create().WithIdentity(schedule.JobType.FullName + ".trigger").WithCronSchedule(schedule.CronExpression)
            .WithDescription(schedule.CronExpression)
            .Build();
    }
}
public class JobSchedule
{
    public Type JobType { get; private set; }

    public string CronExpression { get; private set; }



    public JobSchedule(Type jobType, string cronExpression)
    {
        JobType = jobType ?? throw new ArgumentNullException("jobType");
        CronExpression = cronExpression ?? throw new ArgumentNullException("cronExpression");
    }
}
